package tw.com.msig.b2c.car.common.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import tw.com.msig.b2c.car.common.dao.GenericDao;
import tw.com.msig.b2c.car.common.vo.BaseVo;

public class GenericHibernateDaoImpl<T extends BaseVo> implements GenericDao<T> {

	
	protected SessionFactory sessionFactory;
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	protected Class<? extends T> entityClass;
	
	public GenericHibernateDaoImpl() {
		final ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
		this.entityClass = (Class<T>) type.getActualTypeArguments()[0];
	}
	
	protected Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	
	@Override
	public List<T> findAll() {
		return getSession().createCriteria(entityClass).list();
	}

	@Override
	public T findById(Long id) {
		return (T) getSession().get(entityClass, id);
	}

	@Override
	public void insert(T vo) {
		getSession().save(vo);
	}

	@Override
	public void update(T vo) {
		getSession().update(vo);
	}

	@Override
	public void delete(T vo) {
		getSession().delete(vo);
	}

}
